//
//  JKIndexVC.m
//  chequanbao_ios
//
//  Created by 朱凯 on 2018/1/23.
//  Copyright © 2018年 com.itboye. All rights reserved.
//

#import "JKIndexVC.h"

// service
#import "ByCoreToolLocation.h"              // 定位服务

// vc
#import "ByUIIndexLocationVC.h"             // 定位
#import "ByUIPropertySafetyVC.h"            // 有车一族
#import "JKIndexMyWelfareListVC.h"          // 我的福利列表
#import "ByUIMineWelfareVC.h"               // 我的福利
#import "JKStoreVC.h"                       // 唯优商城
#import "JKShopsVC.h"                       // 折扣上家
#import "ByUIShopsIndexVC.h"
#import "JKShopsDetailVC.h"

// view
#import "ByViewDetailHeaderCarousel.h"      // 轮播视图
#import "ByViewRedPicket.h"                 // 红包
#import "JKViewSearch.h"                    // 搜索

// api
#import "ByApiAppIndex.h"
#import "ByNetConfigApi.h"

// cell
#import "JKCellAppIndexSections.h"          // 首页板块：折扣商家、有车一族、唯优商城、我的福利
#import "JKCellAppIndexActivity.h"          // 首页活动
#import "JKCellAppIndexHotShops.h"          // 首页热门商店-三个
#import "JKCellAppIndexShops.h"             // 首页商店
#import "JKCellAppIndexBanner.h"            // 轮播

// model
#import "ByModelIndexCarousel.h"

#import "ByCoreRefreshGifHeader.h"

@interface JKIndexVC () <UITableViewDelegate,UITableViewDataSource,ByCoreLoactionDelegate,UISearchBarDelegate>

@property (nonatomic, strong) UITableView                   *table;
@property (nonatomic, strong) UIView                        *locationView;
@property (nonatomic, strong) ByViewDetailHeaderCarousel    *carousel;


@property (nonatomic, strong) ByViewRedPicket               *rpView;

// data
@property (nonatomic, strong) NSArray                       *carousels;     // 轮播
@property (nonatomic, strong) NSArray                       *banners;       // 横幅（夹在商品中间）
@property (nonatomic, strong) NSArray                       *activitys;     // 活动
@property (nonatomic, strong) NSArray                       *hots;          // 热门
@property (nonatomic, strong) NSMutableArray                *shops1;        // 商家列表
@property (nonatomic, strong) NSMutableArray                *shops2;        // 商家列表

@end

@implementation JKIndexVC
{
    NSString *_city;            // 定位城市或者选择城市
}
#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self createNaviItems];
    [self createTableView];
    
    [self location];
    
    [self getData];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self setNaviAttributeWithTranslucent:false stateBarLightContent:false];
}

#pragma mark - 定位
- (void)location {
    [ByCoreToolAlert showLoadind:@"正在定位..."];
    ByCoreToolLocation *locationManager = [ByCoreToolLocation shareInstance];
    locationManager.delegate = self;
    [locationManager configLocationService];
    [locationManager startUpdateLoaction];
}
- (void)locationDidComplete:(NSDictionary *)placeInfoDic {
    
    [ByCoreToolAlert hideHud];
    // 更新当前显示的城市
    _city = placeInfoDic[@"city"];
    [self updateLocation];
    // 设置定位城市
    BY_APPDELEGATE.locationCity = _city;
    BY_APPDELEGATE.locationDic = placeInfoDic;
    
}
- (void)locationDidFail:(NSError *)error {
    [ByCoreToolAlert showOnlyText:@"定位失败"];
}
- (void)updateLocation {
    UILabel *cityLabel = [self.locationView viewWithTag:2];
    cityLabel.text = _city;
}


#pragma mark - 请求
- (void)getData {
    
    [self.table.mj_header endRefreshing];
    [ByCoreToolAlert showLoadind:@"正在加载..."];
    
    dispatch_queue_t queue = dispatch_queue_create("my", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    // 轮播
    ByNetParamsModel *params = [ByNetParamsModel new];
    params.position = @"6079";
    [ByApiAppIndex getIndexCarousel:params success:^(ByNetBaseResult *result) {
        self.carousels = result.data;
        self.carousel.imageURLStringDatas = self.carousels;
        dispatch_group_leave(group);
    } failure:^(ByNetBaseResult *result) {
        dispatch_group_leave(group);
    }];
    // 活动
    dispatch_group_enter(group);
    [ByNetConfigApi requestRemoteGlobalConfigSuccess:^(ByNetBaseResult *result) {
        if ([result.data[@"SCROLL_TEXT"] isKindOfClass:[NSArray class]]) {
            self.activitys = [result.data[@"SCROLL_TEXT"] copy];
        }
        dispatch_group_leave(group);
    } failure:^(ByNetBaseResult *result) {
        dispatch_group_leave(group);
    }];
    // 热门店铺（三个）
    dispatch_group_enter(group);
    params = [ByNetParamsModel new];
    params.position = @"6246";
    [ByApiAppIndex getIndexCarousel:params success:^(ByNetBaseResult *result) {
        self.hots = result.data;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.table reloadSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationNone];
        });
        dispatch_group_leave(group);
    } failure:^(ByNetBaseResult *result) {
        dispatch_group_leave(group);
    }];
    // 横幅
    dispatch_group_enter(group);
    params = [ByNetParamsModel new];
    params.position = @"6243";
    [ByApiAppIndex getIndexCarousel:params success:^(ByNetBaseResult *result) {
        self.banners = result.data;
        dispatch_group_leave(group);
    } failure:^(ByNetBaseResult *result) {
        dispatch_group_leave(group);
    }];
    // 商家
    dispatch_group_enter(group);
    params = [ByNetParamsModel new];
    params.position = @"6247";
    [ByApiAppIndex getIndexCarousel:params success:^(ByNetBaseResult *result) {
        NSArray *shops = result.data;
        _shops1 = [NSMutableArray new];
        _shops2 = [NSMutableArray new];
        [shops enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx < 4) {
                [_shops1 addObject:obj];
            } else {
                [_shops2 addObject:obj];
            }
        }]; 
        
        dispatch_group_leave(group);
    } failure:^(ByNetBaseResult *result) {
        dispatch_group_leave(group);
    }];
    
    // 所有请求结束
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [ByCoreToolAlert hideHud];
            [self.table reloadData];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [ByNetConfigApi requestRemoteGlobalConfigSuccess:^(ByNetBaseResult *result) {
                    if ([result.data[@"SCROLL_TEXT"] isKindOfClass:[NSArray class]]) {
                        self.activitys = [result.data[@"SCROLL_TEXT"] copy];
                    }
                    [self.table reloadData];
                } failure:^(ByNetBaseResult *result) {
                }];
            });
        });
    });
}



#pragma mark - 创建视图
- (void)createNaviItems {
    // 搜索
    JKViewSearch *searchView = [[JKViewSearch alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 0.7 - 40, 30)];
    searchView.searchBlock = ^(NSString *searchText) {
        ByUIShopsIndexVC *vc = [ByUIShopsIndexVC new];
        vc.searchName = searchText;
        [self by_normalPush:vc hasNavi:true];
    };
    self.navigationItem.titleView = searchView;
    
    // 定位
    self.locationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 0.2, 30)];
    self.locationView.backgroundColor = [UIColor clearColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(locationTap:)];
    [self.locationView addGestureRecognizer:tap];
    
    UIImageView *downIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    downIcon.image = [UIImage imageNamed:@"首页-下箭头"];
    [self.locationView addSubview:downIcon];
    downIcon.right = self.locationView.width - 10;
    downIcon.y = self.locationView.height / 2;
    downIcon.tag = 1;
    
    UILabel *cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, downIcon.left, self.locationView.height)];
    cityLabel.font = FONT(14);
    cityLabel.text = @"选择";
    cityLabel.textColor = [UIColor blackColor];
    cityLabel.textAlignment = NSTextAlignmentCenter;
    [self.locationView addSubview:cityLabel];
    cityLabel.tag = 2;
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:self.locationView];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 电话
    [self addBYItemviews:@[@"首页-电话"] mode:ByNavigationItemModeImage position:ByNavigationItemPositionModeRight];
}
- (void)createTableView {
    
    self.table = [[UITableView alloc] init];
    self.table.backgroundColor = [UIColor whiteColor];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 49, 0)).priorityMedium();
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-49);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
        }
    }];
    
    
    __weak typeof(self) wself = self;
    self.carousel = [[ByViewDetailHeaderCarousel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * 8 / 15) timerDuration:3];
    self.carousel.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    // 轮播点击
    self.carousel.itemDidTap = ^(NSInteger index) {
        [wself carouselTap:index];
    };
    self.table.tableHeaderView = self.carousel;
    
    
    [self.table registerClass:[JKCellAppIndexSections class] forCellReuseIdentifier:@"sectionsCell"];
    [self.table registerClass:[JKCellAppIndexActivity class] forCellReuseIdentifier:@"activityCell"];
    [self.table registerClass:[JKCellAppIndexHotShops class] forCellReuseIdentifier:@"hotShopsCell"];
    [self.table registerClass:[JKCellAppIndexShops class] forCellReuseIdentifier:@"shops1Cell"];
    [self.table registerClass:[JKCellAppIndexBanner class] forCellReuseIdentifier:@"bannerCell"];
    [self.table registerClass:[JKCellAppIndexShops class] forCellReuseIdentifier:@"shops2Cell"];

    
    self.table.mj_header = [ByCoreRefreshGifHeader headerWithRefreshingBlock:^{
        [wself getData];
    }];

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    /*
     0.4个
     1.超值活动
     2.3个
     3.最多4个商品
     4.轮播
     5.其他商品（去掉前面四个）
     */
    return 6;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        JKCellAppIndexSections *cell = [tableView dequeueReusableCellWithIdentifier:@"sectionsCell"];
        cell.tapBlock = ^(NSInteger index) {
            [self sectionTap:index];
        };
        return cell;
    }
    else if (indexPath.section == 1) {
        JKCellAppIndexActivity *cell = [tableView dequeueReusableCellWithIdentifier:@"activityCell"];
        cell.activitys = _activitys;
        cell.hidden = _activitys.count == 0;
        return cell;
    }
    else if (indexPath.section == 2) {
        JKCellAppIndexHotShops *cell = [tableView dequeueReusableCellWithIdentifier:@"hotShopsCell"];
        cell.hots = _hots;
        cell.hidden = _hots.count == 0;
        return cell;
    }
    else if (indexPath.section == 3) {
        JKCellAppIndexShops *cell = [tableView dequeueReusableCellWithIdentifier:@"shops1Cell"];
        cell.shops = _shops1;
        return cell;
    }
    else if (indexPath.section == 4) {
        JKCellAppIndexBanner *cell = [tableView dequeueReusableCellWithIdentifier:@"bannerCell"];
        cell.banners = _banners;
        return cell;
    }
    else if (indexPath.section == 5) {
        JKCellAppIndexShops *cell = [tableView dequeueReusableCellWithIdentifier:@"shops2Cell"];
        cell.shops = _shops2;
        return cell;
    }
    
    
    return UITableViewCell.new;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return [tableView fd_heightForCellWithIdentifier:@"sectionsCell" cacheByIndexPath:indexPath configuration:^(id cell) {
        }];
    }
    else if (indexPath.section == 1) {
        return _activitys.count == 0 ? 0 : [tableView fd_heightForCellWithIdentifier:@"activityCell" cacheByIndexPath:indexPath configuration:^(JKCellAppIndexActivity *cell) {
            cell.activitys = _activitys;
        }];
    }
    else if (indexPath.section == 2) {
        return _hots.count == 0 ? 0 : [tableView fd_heightForCellWithIdentifier:@"hotShopsCell" cacheByIndexPath:indexPath configuration:^(JKCellAppIndexHotShops *cell) {
            cell.hots = _hots;
        }];
    }
    else if (indexPath.section == 3) {
        return _shops1.count == 0 ? 0 : (10 + (SCREEN_WIDTH - 50) / 2 + 10 + 15 + 5 + 15 + 10) * _shops1.count / 2;
//        return _shops1.count == 0 ? 0 : [tableView fd_heightForCellWithIdentifier:@"shops1Cell" cacheByIndexPath:indexPath configuration:^(JKCellAppIndexShops *cell) {
//            cell.shops = _shops1;
//        }];
    }
    else if (indexPath.section == 4) {
        return _banners.count == 0 ? 0 : SCREEN_WIDTH / 4;
    }
    else if (indexPath.section == 5) {
        
        return _shops2.count == 0 ? 0 : (10 + (SCREEN_WIDTH - 50) / 2 + 10 + 15 + 5 + 15 + 10) * _shops2.count / 2;
//        return _shops2.count == 0 ? 0 : [tableView fd_heightForCellWithIdentifier:@"shops2Cell" cacheByIndexPath:indexPath configuration:^(JKCellAppIndexShops *cell) {
//            cell.shops = _shops2;
//        }];
    }
    
    
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return UIView.new;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return UIView.new;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 横幅
    if (indexPath.section == 4) {
        ByModelIndexCarousel *model = self.banners.firstObject;
        if (![model.storeid isEqualToString:@"-1"] && ![model.storeid isEqualToString:@"0"] && model.storeid.length != 0) {
            JKShopsDetailVC *vc = [[JKShopsDetailVC alloc] init];
            vc.seller_id = model.storeid;
            [self by_normalPush:vc hasNavi:YES];
        }
    }
   
}


#pragma mark - 点击事件
// 打电话
- (void)rightItemsAction:(NSInteger)rightIndex {
    
    NSString *tel1 = [ByNetConfig getCustomerPhone];
    NSString *tel = [NSString stringWithFormat:@"telprompt://%@",tel1];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tel]];
        });
    });
}
// 定位视图点击
- (void)locationTap:(UITapGestureRecognizer *)tap {
    
    ByUIIndexLocationVC *vc = [[ByUIIndexLocationVC alloc] init];
    [self by_normalPush:vc hasNavi:YES];
    vc.locationDidSelected = ^(ByModelLocationCity *cityModel) {
        BY_APPDELEGATE.selectedCityModel = cityModel;
        _city = cityModel.city;
        [self updateLocation];
    };
}
// 轮播点击
- (void)carouselTap:(NSInteger)index {
    ByModelIndexCarousel *model = self.carousel.imageURLStringDatas[index];
    if (![model.storeid isEqualToString:@"-1"] && ![model.storeid isEqualToString:@"0"] && model.storeid.length != 0) {
        JKShopsDetailVC *vc = [[JKShopsDetailVC alloc] init];
        vc.seller_id = model.storeid;
        [self by_normalPush:vc hasNavi:YES];
    }
    
}
// 板块点击
- (void)sectionTap:(NSInteger)index {
    
    switch (index) {
        case 0:
        {
            JKShopsVC *vc = [JKShopsVC new];
            [self by_normalPush:vc hasNavi:YES];
        }
            break;
        case 1:
        {
            if (!BY_USER) {
                ByUILoginVC *vc = [[ByUILoginVC alloc] init];
                ByBaseNaviController *navi = [[ByBaseNaviController alloc] initWithRootViewController:vc];
                [self presentViewController:navi animated:YES completion:nil];
                return;
            }
            
            ByUIPropertySafetyVC *vc = [[ByUIPropertySafetyVC alloc] init];
            [self by_normalPush:vc hasNavi:YES];
        }
            break;
        case 2:
        {
            JKStoreVC *vc = [JKStoreVC new];
            [self by_normalPush:vc hasNavi:YES];
        }
            break;
        case 3:
        {
            JKIndexMyWelfareListVC *vc = [JKIndexMyWelfareListVC new];
            [self by_normalPush:vc hasNavi:true];
        }
            break;
        default:
            break;
    }
}

#pragma mark - 逻辑
// 是否需要展示红包
#define KIsFirstUse @"isFirstUse"
- (BOOL)needShowRedPacket {
    
    NSNumber *isFirstUse = [ByCoreCacheSqlite3 getValueWithKey:KIsFirstUse];
    // 没有设置过值，就说明是第一次
    if ( isFirstUse == nil) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_after(dispatch_time(0, NSEC_PER_SEC * 0.5), dispatch_get_main_queue(), ^{
                [self.rpView show];
            });
        });
        [ByCoreCacheSqlite3 setObjectWithKey:KIsFirstUse value:@YES];
        return YES;
    } else {
        return NO;
    }
    
}



#pragma mark - 懒加载
- (ByViewRedPicket *)rpView {
    
    if (!_rpView) {
        _rpView = [[ByViewRedPicket alloc] init];
        __weak typeof(self) wself = self;
        _rpView.rpTapBlock = ^ {
            [wself by_normalPush:[ByUIMineWelfareVC new] hasNavi:YES];
        };
    }
    return _rpView;
}
@end
